"""
SqlAlchermy 数据查询懒加载技术
"""
import os
import sys

path = os.path.dirname(__file__)
sys.path.append(os.path.join(path, '..'))

import random
from faker import Faker
from conf.mysql_config import SESSION
from orm.demo8 import User, UserAddress


def add_data():
    fake = Faker(locale='zh_CN')
    users = []
    for _ in range(10):
        user = User(name=fake.name())
        user.address_list = [UserAddress(address=fake.address()) for _ in range(random.randint(1, 20))]
        users.append(user)
    SESSION.add_all(users)
    SESSION.commit()


def search_data():
    user = SESSION.query(User).get(2)
    # <class 'sqlalchemy.orm.dynamic.AppenderQuery'>
    # print(type(user.address_list))
    user.address_list.append(UserAddress(address='四川省测试地址'))
    SESSION.commit()
    si_chuan_address_list = user.address_list.filter(UserAddress.address.like('四川省%')).all()
    print(si_chuan_address_list)


if __name__ == '__main__':
    search_data()
